package com.tl.sun.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tl.sun.AppContext;
import com.tl.sun.AppManager;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.helper.UIHelper;
import com.tl.sun.manager.MDAccountMgr;
import com.tl.sun.manager.MDUserMgr;
import com.tl.sun.model.BaseModel;
import com.tl.sun.model.ExceedUserEnetity;
import com.tl.sun.model.SessionEnetity;
import com.tl.sun.model.UserEnetity;
import com.tl.sun.utils.DeviceUuidFactory;
import com.tl.sun.utils.ToastUtil;
import com.tl.sun.utils.common.AppUtils;
import com.tl.sun.utils.common.MD5Util;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 16/10/13.
 */

public class BindPhoneSuccessActivity extends BaseActivity {
    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.tv_bind_submit)
    TextView mTvBindSubmit;
    private String name;
    private String password;
    private boolean regist =false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_bind_phone_success);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            name = bundle.getString("name");
            password = bundle.getString("pass");
            regist =bundle.getBoolean("regist");
        }
        init();
    }


    public void init() {
        mTvGenericTitle.setText("绑定手机号");
    }

    @OnClick({R.id.rl_generic_back, R.id.tv_bind_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_generic_back:
                onBackPressed();
                break;
            case R.id.tv_bind_submit:
                if(regist) {
                    login(name, password);
                }
                finish();
                break;
        }
    }

    /**
     * 登录
     *
     * @param name
     * @param password
     */
    public void login(final String name, final String password) {

        AppUtils.AppInfo appInfo = AppUtils.getAppInfo(this);
        int versionCode = 1;
        if (appInfo != null) {
            versionCode = appInfo.getVersionCode();
        }


        HashMap<String, String> map = new HashMap<>();
        map.put("username", name);
        map.put("password", password);
        map.put("device_token", MDAccountMgr.getInstance().getDeviceToken());
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        JSONObject jsonObject = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/login_v2")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModels = gson.fromJson(s, BaseModel.class);
                        if (baseModels.getRet().equals("0")) {
                            Type userType = new TypeToken<BaseModel<SessionEnetity>>() {
                            }.getType();
                            BaseModel<SessionEnetity> baseModel;
                            try {
                                baseModel = gson.fromJson(s, userType);
                            } catch (JsonSyntaxException e) {
                                baseModel = gson.fromJson(s, BaseModel.class);
                            }
                            SessionEnetity sessionInfo = baseModel.getData();
                            MDAccountMgr.getInstance().setSessionId(sessionInfo.getSession());
                            UserEnetity user = sessionInfo.getUserInfo();
                            MDUserMgr.getInstance().setAvatar(user.getAvatar());
                            MDUserMgr.getInstance().setAwardFlag(user.getAward_flag());
                            MDUserMgr.getInstance().setId(user.getId());
                            MDUserMgr.getInstance().setUsername(user.getUsername());
                            MDUserMgr.getInstance().setShowName(user.getShowNmae());
                            MDUserMgr.getInstance().setNickname(user.getNick_name());
                            MDUserMgr.getInstance().setChange(user.getChange());
                            MDUserMgr.getInstance().setEmail(user.getEmail());
                            MDUserMgr.getInstance().setPhone(user.getPhone());
                            MDUserMgr.getInstance().setMoney(Double.valueOf(user.getMoney()));
                            MDUserMgr.getInstance().setLastTime(user.getLast_time());
                            MDUserMgr.getInstance().setLastTimeType(user.getLast_time_type());
                            MDUserMgr.getInstance().setStatus(user.getStatus());
                            MDUserMgr.getInstance().setToken(user.getToken());
                            MDUserMgr.getInstance().setTime(user.getnVipTime() );
                            MDUserMgr.getInstance().setsTime(user.getsVipTime() );
                            MDUserMgr.getInstance().setCoupoum(user.getCoupoum());
                            MDUserMgr.getInstance().setLogin(true);//保存到类

                            MDUserMgr.getInstance().setThreeDayExpire(user.getThreeDayExpire());
                            MDAccountMgr.getInstance().setLogin(true);//保存到内存
                            MDAccountMgr.getInstance().setLoginName(user.getShowNmae());
                            MDAccountMgr.getInstance().setLoginPwd(password);

                            MDAccountMgr.getInstance().setPassowrd(true);
                            MDAccountMgr.getInstance().writeToCache(BindPhoneSuccessActivity.this);
                            AppManager.getAppManager().finishActivity(LoginActivity.class);

                            Intent login = new Intent(BindPhoneSuccessActivity.this, MainActivity.class);
                            startActivity(login);
                            finish();
                        } else if (baseModels.getRet().equals("1")) {
                            Type exceed = new TypeToken<BaseModel<List<ExceedUserEnetity>>>() {
                            }.getType();
                            BaseModel<List<ExceedUserEnetity>> exceeModel;
                            try {
                                exceeModel = gson.fromJson(s, exceed);
                            } catch (JsonSyntaxException e) {
                                exceeModel = gson.fromJson(s, BaseModel.class);
                            }
                            if (exceeModel.getCode().equals("overtop")) {
                                UIHelper.showTerminal(BindPhoneSuccessActivity.this, exceeModel.getData(), UIHelper.LOGIN_DIALOG,"2");
                            } else {
                                ToastUtil.showToast(baseModels.getMsg());
                            }
                        } else {
                            ToastUtil.showToast(baseModels.getMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        ToastUtil.showToast("网络请求失败");

                    }

                });
    }
}
